package com.andon.microcellsimulator.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.andon.microcellsimulator.R;
import com.andon.microcellsimulator.common.util.LogUtil;
import com.andon.microcellsimulator.common.util.ZnkActivityUtil;
import com.andon.microcellsimulator.common.zxing.activity.CaptureActivity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ScanMemberIDActivity extends CaptureActivity implements View.OnClickListener {

    private final String TAG_CLASS_NAME = this.getClass().getSimpleName();

    // 返回
    private ImageView mReturn;

    private Dialog mProgressDialog;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    returnResult(msg.obj.toString());
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初期加载画面显示
        setContentView(R.layout.activity_scan_member_id);

        // 设置通知栏透明效果
        setStatusBar(R.color.theme);

        mReturn = (ImageView) findViewById(R.id.scan_cancel);
        mReturn.setOnClickListener(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        // 锁屏或者Home键退出扫码页
        if (ZnkActivityUtil.getContext() == ScanMemberIDActivity.this) {
            ZnkActivityUtil.finishActivity();
        }
    }

    @Override
    protected int getViewFinderViewId() {
        return R.id.scan_viewfinder_view;
    }

    @Override
    protected int getSurfaceViewId() {
        return R.id.scan_preview_view;
    }

    @Override
    protected void scanFinish(String scanResult) {

        if (scanResult != null && scanResult.startsWith("http")) {
            mProgressDialog = ZnkActivityUtil.getLoadingDialog(this, "解析中");
            mProgressDialog.show();
            UrlContentReader reader = new UrlContentReader(scanResult);
            reader.start();
        } else {
            returnResult(scanResult);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.scan_cancel:
                ZnkActivityUtil.finishActivity();
                break;
        }
    }

    private void returnResult(String result) {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("result", result);
        resultIntent.putExtras(bundle);
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    class UrlContentReader extends Thread {

        private String mUrl;

        public UrlContentReader(String url) {
            mUrl = url;
        }

        @Override
        public void run() {

            StringBuilder strBuf = new StringBuilder();

            try {
                boolean redirect = false;
                URL url = new URL(mUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置网络获取时间间隔，超出时间后跳出
                conn.setRequestMethod("POST");
                conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1");
                conn.setRequestProperty("accept-language", "zh-CN");
                conn.setConnectTimeout(30000);
                conn.setReadTimeout(30000);
                conn.setInstanceFollowRedirects(true);

                int state = conn.getResponseCode();
                LogUtil.i("ResponseCode:" + state + " url:" + conn.getURL().toString() + " content:" + conn.getResponseMessage());

                if (state == HttpURLConnection.HTTP_MOVED_TEMP
                        || state == HttpURLConnection.HTTP_MOVED_PERM) {
                    redirect = true;
                }

                if (redirect) {

                    // get redirect url from "location" header field
                    String newUrl = conn.getHeaderField("Location");

                    // get the cookie if need, for login
                    String cookies = conn.getHeaderField("Set-Cookie");

                    // open the new connnection again
                    conn = (HttpURLConnection) new URL(newUrl).openConnection();
                    conn.setRequestProperty("Cookie", cookies);
                    conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1");
                    conn.setRequestProperty("accept-language", "zh-CN");
                    conn.setConnectTimeout(30000);
                    conn.setReadTimeout(30000);
                    conn.setInstanceFollowRedirects(true);

                    state = conn.getResponseCode();
                    LogUtil.i("ResponseCode:" + state + " url:" + conn.getURL().toString() + " content:" + conn.getResponseMessage());

                }

                if (state == 200) {
                    String regexString = "var jump_url=\\\"([\\S]+)\\\"";
                    Pattern pattern = Pattern.compile(regexString);
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(conn.getInputStream(),
                                    "utf-8"));// 转码。
                    String line = null;
                    String tagurl = null;
                    while ((line = reader.readLine()) != null) {
                        Matcher matcher = pattern.matcher(line);
                        if (matcher.find()) {
                            tagurl = matcher.group(1);
                            LogUtil.i("tagurl:" + tagurl);
                            break;
                        }
                    }

                    reader.close();

                    if (!TextUtils.isEmpty(tagurl)) {
                        // get the cookie if need, for login
                        String cookies = conn.getHeaderField("Set-Cookie");
                        // open the new connnection again
                        conn = (HttpURLConnection) new URL(tagurl).openConnection();
                        conn.setRequestProperty("Cookie", cookies);
                        conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1");
                        conn.setRequestProperty("accept-language", "zh-CN");
                        conn.setConnectTimeout(30000);
                        conn.setReadTimeout(30000);
                        conn.setInstanceFollowRedirects(true);

                        state = conn.getResponseCode();
                        LogUtil.i("ResponseCode:" + state + " url:" + conn.getURL().toString() + " content:" + conn.getResponseMessage());

                        String resRegexString = "\\{\\\"deviceID\\\":\\\"[\\S]+\\\",\\\"rsa\\\":\\\"[\\S]+\\\"\\}";

                        Pattern pattern1 = Pattern.compile(resRegexString);

                        BufferedReader reader1 = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(), "utf-8"));// 转码。
                        while ((line = reader1.readLine()) != null) {
                            line = line.replace("&quot;", "\"");
                            Matcher matcher = pattern1.matcher(line);
                            if (matcher.find()) {
                                strBuf.append(matcher.group(0));
                                break;
                            }
                        }

                        reader1.close();
                    }

                    LogUtil.i("获取文本成功:" + strBuf.toString());
                }

            } catch (Exception e) {
                LogUtil.w(e.toString());
            } finally {
                Message msg = mHandler.obtainMessage();
                msg.what = 0;
                msg.obj = strBuf.toString();
                mHandler.sendMessage(msg);
            }

        }
    }
}